package com.tuanzi.loan.security;

import com.tuanzi.loan.security.AuthenticationFailureType;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Ray 2017/10/01
 */
@Component
public class LoanInvalidSessionStagegy implements InvalidSessionStrategy {

    public static final String EXPIRED_URL = "/login.xhtml?failureType=" + AuthenticationFailureType.SESSION_TIMEOUT;
    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    private boolean createNewSession = true;

    public LoanInvalidSessionStagegy() {
    }

    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (this.createNewSession) {
            request.getSession();
        }
        this.redirectStrategy.sendRedirect(request, response, EXPIRED_URL);
    }

    public void setCreateNewSession(boolean createNewSession) {
        this.createNewSession = createNewSession;
    }
}
